﻿using Common;
using Host;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AXImServer
{
    public class LoginManager
    {
        private static LoginManager loginmanager = new LoginManager();
        private string Password = string.Empty;
        private const int SaltLenght = 32;
        private byte[] Salt = new byte[SaltLenght];

        private Dictionary<long, string> UserId2CheckCode = new Dictionary<long, string>();

        private LoginManager()
        {
            Password = TokenHelper.GetInstance().GetRandomToken(128);
            Random random = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < SaltLenght; i++)
            {
                Salt[i] = (byte)random.Next(byte.MaxValue);
            }
        }

        public static LoginManager GetInstance()
        {
            return loginmanager;
        }

        private long _token_term = 3600;

        /// <summary>
        /// 小票的有效时间
        /// </summary>
        public long TokenTerm
        {
            get { return _token_term; }
            set { _token_term = value; }
        }

        /// <summary>
        /// 获取用户的Token与Id的对应关系
        /// (小用户数量的解决方案，如果数量很大，需要修改这部分逻辑)
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string Login(long userid)
        {
            string check_code = TokenHelper.GetInstance().GetRandomToken(16);
            UserId2CheckCode[userid] = check_code;

            string token = GetTokenFormat(userid, GetCurrentSecond() + TokenTerm, check_code);
            return TokenHelper.GetInstance().EncryptionToken(token, Password, Salt);
        }

        /// <summary>
        /// 账号登出
        /// </summary>
        /// <param name="userid"></param>
        public void Logout(long userid)
        {
            UserId2CheckCode[userid] = string.Empty;
        }

        /// <summary>
        /// 根据Token获取用户Id
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public long GetUserIdByToken(string token)
        {
            string data = TokenHelper.GetInstance().DecryptionToken(token, Password, Salt);
            var list = data.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

            if (list == null || list.Length < 3)
                return -1;

            long token_term = -1;
            if (!long.TryParse(list[1], out token_term) || token_term < GetCurrentSecond())
                return -1;

            long user_id = -1;
            if (!long.TryParse(list[0], out user_id))
                return -1;

            if (!UserId2CheckCode.ContainsKey(user_id))
                return -1;

            string check_code = UserId2CheckCode[user_id];
            if (check_code != list[2])
                return -1;

            return user_id;
        }

        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        public User GetCurrentUser()
        {
            return null;
        }

        /// <summary>
        /// 获取明文格式化的Token
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="expiration_time"></param>
        /// <param name="checkcode"></param>
        /// <returns></returns>
        private string GetTokenFormat(long userid, long expiration_time, string checkcode)
        {
            return string.Format("{0}:{1}:{2}", userid, expiration_time, checkcode);
        }

        /// <summary>
        /// 获取当前的毫秒
        /// </summary>
        /// <returns></returns>
        public long GetCurrentMillisecond()
        {
            return DateTime.Now.Ticks / 10000;
        }

        /// <summary>
        /// 获取当前的秒数
        /// </summary>
        /// <returns></returns>
        public long GetCurrentSecond()
        {
            return DateTime.Now.Ticks / 10000000;
        }
    }
}
